import 'package:flutter/material.dart';

class PageViewDemo extends StatefulWidget {
  @override
  _PageViewDemoState createState() => _PageViewDemoState();
}

class _PageViewDemoState extends State<PageViewDemo> {
  late PageController _pageController;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView Demo'),
        backgroundColor: Colors.blue,
      ),
      body: Column(
        children: [
          // 页面指示器
          Container(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(5, (index) {
                return Container(
                  margin: EdgeInsets.symmetric(horizontal: 4),
                  width: 10,
                  height: 10,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentPage == index ? Colors.blue : Colors.grey,
                  ),
                );
              }),
            ),
          ),

          // PageView 主体
          Expanded(
            child: PageView(
              controller: _pageController,
              onPageChanged: (int page) {
                setState(() {
                  _currentPage = page;
                });
              },
              children: [
                _buildPage(0, '首页', Icons.home, Colors.blue),
                _buildPage(1, '搜索', Icons.search, Colors.green),
                _buildPage(2, '收藏', Icons.favorite, Colors.red),
                _buildPage(3, '设置', Icons.settings, Colors.orange),
                _buildPage(4, '个人', Icons.person, Colors.purple),
              ],
            ),
          ),

          // 控制按钮
          Container(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _currentPage > 0
                    ? () => _pageController.previousPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                      )
                    : null,
                  child: Text('上一页'),
                ),
                Text('第 ${_currentPage + 1} 页'),
                ElevatedButton(
                  onPressed: _currentPage < 4
                    ? () => _pageController.nextPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                      )
                    : null,
                  child: Text('下一页'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPage(int index, String title, IconData icon, Color color) {
    return Container(
      color: color.withOpacity(0.1),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 80, color: color),
          SizedBox(height: 20),
          Text(
            title,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: 10),
          Text(
            '这是第 $index 页',
            style: TextStyle(fontSize: 16, color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }
}

// 高级 PageView 示例 - 包含多种 PageView 类型
class AdvancedPageViewDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          title: Text('高级 PageView Demo'),
          backgroundColor: Colors.blue,
          bottom: TabBar(
            tabs: [
              Tab(text: '基础'),
              Tab(text: '滚动'),
              Tab(text: '自定义'),
              Tab(text: '垂直'),
            ],
          ),
        ),
        body: TabBarView(
          children: [
            // 1. 基础 PageView
            _buildBasicPageView(),

            // 2. 可滚动 PageView
            _buildScrollablePageView(),

            // 3. 自定义 PageView
            _buildCustomPageView(),

            // 4. 垂直 PageView
            _buildVerticalPageView(),
          ],
        ),
      ),
    );
  }

  // 基础 PageView
  Widget _buildBasicPageView() {
    return PageView(
      children: [
        Container(
          color: Colors.blue[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.looks_one, size: 80, color: Colors.blue),
                Text('基础 PageView - 页面 1', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
        Container(
          color: Colors.green[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.looks_two, size: 80, color: Colors.green),
                Text('基础 PageView - 页面 2', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
        Container(
          color: Colors.red[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.looks_3, size: 80, color: Colors.red),
                Text('基础 PageView - 页面 3', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 可滚动 PageView.builder
  Widget _buildScrollablePageView() {
    return PageView.builder(
      itemCount: 10,
      itemBuilder: (context, index) {
        Color color = Colors.primaries[index % Colors.primaries.length];
        return Container(
          color: color,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.pages,
                  size: 80,
                  color: color,
                ),
                Text(
                  '可滚动 PageView - 页面 ${index + 1}',
                  style: TextStyle(fontSize: 20),
                ),
                Text('总共 10 页'),
              ],
            ),
          ),
        );
      },
    );
  }

  // 自定义 PageView - 带缩放效果
  Widget _buildCustomPageView() {
    PageController controller = PageController(viewportFraction: 0.8);

    return PageView.builder(
      controller: controller,
      itemCount: 8,
      itemBuilder: (context, index) {
        Color color = Colors.primaries[index % Colors.primaries.length];
        return AnimatedBuilder(
          animation: controller,
          builder: (context, child) {
            double value = 1.0;
            if (controller.position.haveDimensions) {
              value = controller.page! - index;
              value = (1 - (value.abs() * 0.3)).clamp(0.0, 1.0);
            }
            return Center(
              child: Container(
                height: Curves.easeInOut.transform(value) * 400,
                width: Curves.easeInOut.transform(value) * 300,
                color: color,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.star,
                        size: 60,
                        color: Colors.white,
                      ),
                      Text(
                        '页面 ${index + 1}',
                        style: TextStyle(
                          fontSize: 24,
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  // 垂直 PageView
  Widget _buildVerticalPageView() {
    return PageView(
      scrollDirection: Axis.vertical,
      children: [
        Container(
          color: Colors.orange[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.arrow_upward, size: 80, color: Colors.orange),
                Text('垂直 PageView - 向上滑动', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
        Container(
          color: Colors.purple[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.arrow_downward, size: 80, color: Colors.purple),
                Text('垂直 PageView - 向下滑动', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
        Container(
          color: Colors.teal[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.swap_vert, size: 80, color: Colors.teal),
                Text('垂直 PageView - 第三页', style: TextStyle(fontSize: 20)),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

// PageView 与 TabBar 联动示例
class PageViewWithTabDemo extends StatefulWidget {
  @override
  _PageViewWithTabDemoState createState() => _PageViewWithTabDemoState();
}

class _PageViewWithTabDemoState extends State<PageViewWithTabDemo>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late PageController _pageController;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _pageController = PageController();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView 与 Tab 联动'),
        backgroundColor: Colors.blue,
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(icon: Icon(Icons.home), text: '首页'),
            Tab(icon: Icon(Icons.search), text: '搜索'),
            Tab(icon: Icon(Icons.favorite), text: '收藏'),
            Tab(icon: Icon(Icons.person), text: '我的'),
          ],
          onTap: (index) {
            _pageController.animateToPage(
              index,
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          },
        ),
      ),
      body: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
            _tabController.animateTo(index);
          });
        },
        children: [
          _buildTabPage('首页', Icons.home, Colors.blue),
          _buildTabPage('搜索', Icons.search, Colors.green),
          _buildTabPage('收藏', Icons.favorite, Colors.red),
          _buildTabPage('我的', Icons.person, Colors.purple),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          _pageController.animateToPage(
            index,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
          BottomNavigationBarItem(icon: Icon(Icons.search), label: '搜索'),
          BottomNavigationBarItem(icon: Icon(Icons.favorite), label: '收藏'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }

  Widget _buildTabPage(String title, IconData icon, Color color) {
    return Container(
      color: color.withOpacity(0.1),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 80, color: color),
          SizedBox(height: 20),
          Text(
            title,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: 10),
          Text(
            'PageView 与 TabBar 联动示例',
            style: TextStyle(fontSize: 16, color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }
}

// 使用示例
void main() {
  runApp(MaterialApp(
    title: 'PageView Demo',
    debugShowCheckedModeBanner: false,
    home: PageViewMainDemo(),
  ));
}

class PageViewMainDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView 示例合集'),
        backgroundColor: Colors.blue,
      ),
      body: ListView(
        padding: EdgeInsets.all(16),
        children: [
          _buildDemoCard(
            context,
            '基础 PageView',
            '包含页面指示器和控制按钮',
            Icons.book,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => PageViewDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            '高级 PageView',
            '展示多种 PageView 类型',
            Icons.auto_awesome,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AdvancedPageViewDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            'PageView 与 Tab 联动',
            'PageView 与 TabBar、BottomNavigationBar 联动',
            Icons.link,
            () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => PageViewWithTabDemo()),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDemoCard(BuildContext context, String title, String description,
      IconData icon, VoidCallback onTap) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 8),
      child: ListTile(
        leading: Icon(icon, size: 40, color: Colors.blue),
        title: Text(
          title,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        subtitle: Text(description),
        trailing: Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }
}
